package com.example.gateway.filters;

import com.example.gateway.config.AuthProperties;
import com.example.gateway.config.JwtProperties;
import com.example.gateway.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final JwtProperties jwtProperties;
    private final JwtUtil jwtUtil;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入全局过滤器");
        // 1.获取request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())) {
            // 不需要做登录拦截 放行
            return chain.filter(exchange);
        }

        // 3.获取token
        String token = null;
        List<String> headers = request.getHeaders().get("authentication");
        System.out.println("heaers:"+ headers);
        if (headers != null && !headers.isEmpty()) {
            token = headers.get(0);
        }
        log.info("token:{}",token);
        // 4.校验并解析token
        String userId = null;
        String role = null;
        try {
            Claims claims = jwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            log.info("claims:{}",claims);
             userId = claims.get("id").toString();
            role = claims.get("role").toString();
        } catch (Exception e) {
            log.error("token无效");
            // token无效 拦截，设置响应状态码为401
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 5.传递用户信息
        String userInfo = userId.toString();
        String userRole=role.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(r ->
                        r.header("user-info", userInfo)
                                .header("user-role",userRole))

                .build();
        // 6.放行
        return chain.filter(swe);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
